<?php

class logCAr extends CActiveRecord
{
    /**
     * @var 需要监看的字段，是一个key为字段名，value为中文名称的数组
     */
    public $monitorColumnArr;
    public $orginArr; //jobs新加的
    public $newArr; //jobs新加的
    public $orginStr;


    //更新前
    public function beforesave()
    {
        $monitorColumnArr = $this->eventCallMinitorSetting();
        if ($monitorColumnArr)
        {
            $oldRecord = static::model()->findByPk($this->getPrimaryKey()); //要查出老的记录
            foreach ($monitorColumnArr['column'] as $key => $value) $this->orginArr[$key] = $oldRecord->$key;
            if (isset($monitorColumnArr['auditColumn'])){
                foreach ($monitorColumnArr['auditColumn'] as $key => $value) $this->orginStr.= $oldRecord->$value;
            }
            if (isset($monitorColumnArr['needToDealWith'])){
                foreach ($monitorColumnArr['needToDealWith'] as $key => $value) $this->orginStr.= static::auditToDealWith($oldRecord,$value);
            }
        }
        return true;
    }
    //更新后
    public function aftersave()
    {
        $monitorColumnArr = $this->eventCallMinitorSetting();
        foreach ($monitorColumnArr['column'] as $key => $value) $this->newArr[$key] = $this->$key;
        $this->saves();
        return true;
    }
    //删除前
    public function beforeDelete()
    {
        $monitorColumnArr = $this->eventCallMinitorSetting();
        if ($monitorColumnArr)
        {
            $oldRecord = static::model()->findByPk($this->getPrimaryKey()); //要查出老的记录
            foreach ($monitorColumnArr['column'] as $key => $value) $this->orginArr[$key] = $oldRecord->$key;
        }
        return true;
    }
    //删除后
    public function afterdelete()
    {
        $monitorColumnArr = $this->eventCallMinitorSetting();
        $this->saves(1);
        return true;
    }


    public function saves($type=0)
    {
        $controller = Yii::app()->controller->id ; //控制器
        $action = Yii::app()->controller->Action->id;//动作名称
        $name =  Yii::app()->session['admin_real_name']; //用户真实姓名
        $admin_id =  Yii::app()->session['admin_id']; //用户id
        $pdate = time();//删除日期
        $recid =  $this->getPrimaryKey();  //记录id
        if($type==1)
            $type= "delete";   //删除
        else
            $type =  $this->scenario ;   //操作类型(update insert)
        $module =  Yii::app()->controller->module->id ; //模块名称
        //查询资源名称
        $criteria=new CDbCriteria;
        $criteria->select='name';
        $criteria->limit='1';
        $criteria->condition='module=:module and controller=:controller and action=:action';
        $criteria->params=array(':module'=>$module,':controller'=>$controller,':action'=>$action);
        $rs=Resource::model()->find($criteria);
        $resName =  $rs->name;

        if( $resName=="androidpclist" or ($module=="shouyou" and $controller=="game" and $action=="onestep") ){
            return true;
        }
        //存入日志记录表
        $log = new  admin_log;
        $log ->resName  = $resName;
        $log ->controller = $controller;
        $log ->module = $module;
        $log ->action = $action;
        $log ->name = $name;
        $log ->admin_id = $admin_id;
        $log ->recid = $recid;
        $log ->type = $type;
        $log ->pdate = $pdate;
        $mem = $this->whichColumnsToRecord($type);
        $log->mem = $mem;
        $log->mark = trim($mem) ? 1 : 0;
        $log ->save();

        if ($this->monitorColumnArr){
            $apiData = array(
                'author'=>$name,
                'department'=>$this->monitorColumnArr['department'],
                'app'=>$module.','.$controller.','.$action,
                'action'=>$type,
                'jsondiff'=>$mem,
                'recid'=>$recid,
                'addtime'=>time(),
            );
            if (trim($mem)) self::adminLogAdd($apiData);
        }

        if ($type!='delete'){
            $auditStr='';
            $auditData=array();
            $monitorColumnArr = $this->eventCallMinitorSetting();
            if (isset($monitorColumnArr['plateId'])){
                //正常无需处理的字段 直接拼接
                if (isset($monitorColumnArr['auditColumn']))foreach ($monitorColumnArr['auditColumn'] as $key => $value) $auditStr.=$this->$value;
                /*
                 * 每个模型  只要有需要审核的内容
                 * 都需要加一个 auditToDealWith 用于处理特殊字段
                 * 2个参数  第一个 是通过id查询出来的一大堆对象信息   第二个就是要处理的字段名
                 * */
                if (isset($monitorColumnArr['needToDealWith']))foreach ($monitorColumnArr['needToDealWith'] as $key => $value) $auditStr.=static::auditToDealWith($this,$value);
                $auditData['content']=$auditStr;
                print_r($auditStr);die;
                $auditData['plateId']=$monitorColumnArr['plateId'];
                $auditData['resourceId']=$recid;
                $auditData['siteId']=1;//1.游侠  3.多特 4.369
                $auditData['url']=static::auditToDealWith($this,'URL');
                if ($this->orginStr!=$auditStr)self::adminAuditToApi($auditData);
            }
        }
    }

    //jobs 2019-07-16写的 记录新的东西，如果以下字段被修改了，那么记录进新的字段
    public function whichColumnsToRecord($type)
    {
        $mem = array();
        if ($this->monitorColumnArr) //手游的库配置，并且是下载表
        {
            if ($type == 'update') //如果是删除，记录删除前的数值
            {
                $mark = 0;
                foreach ($this->monitorColumnArr['column'] as $key => $value)
                {
                    if ($this->orginArr[$key] != $this->newArr[$key])
                    {
                        $mark = 1;
                        $mem[] = $value.'：<del>'.$this->orginArr[$key]."</del> -> ".$this->newArr[$key];
                    }
                    else
                    {
                        $mem[] = $value.'：'.$this->orginArr[$key];
                    }
                }
                if (!$mark) $mem = array();
            }
            elseif ($type == 'insert') //如果是添加
            {
                foreach ($this->monitorColumnArr['column'] as $key => $value) $mem[] = '[增]'.$value.'：'.$this->newArr[$key];
            }
            elseif ($type == 'delete')
            {
                foreach ($this->monitorColumnArr['column'] as $key => $value) $mem[] = '[删]'.$value.'：'.$this->orginArr[$key];
            }
        }

        return implode("\r\n",$mem);
    }

    /** 设计的是需要被覆盖的
     * @return 需要监看的字段，是一个key为字段名，value为中文名称的数组
     */
    public function getMonitorColumnArr()
    {
        return $this->monitorColumnArr;
    }

    public function eventCallMinitorSetting()
    {
        if (!$this->monitorColumnArr) $this->getMonitorColumnArr();
        return $this->monitorColumnArr;
    }

    public function adminLogAdd($data)
    {
        $resources = self::adminLogSign($data);

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, "http://api.ali213.net/summarylog/logApi.php");
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, array('data'=>json_encode($resources)));
        curl_setopt($curl, CURLOPT_TIMEOUT, 2);
        $resultStr = curl_exec($curl);
        curl_close($curl);
        return $resultStr;
    }

    public function adminAuditToApi($data)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, "http://121.199.19.193:808/admin/monitor/textmonitor/send");
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_TIMEOUT, 2);
        $resultStr = curl_exec($curl);
        curl_close($curl);
        return $resultStr;
    }


    public function adminLogSign($data){
        $strSalt = '28c8edde3d61a0411511d3b1866f0636';
        ksort($data);
        $strVal = http_build_query($data, '', '&');
        $strVal = str_replace('+', '%20', $strVal);//php5.3不支持PHP_QUERY_RFC3986,手动替换一下
        $sign = md5($strVal . $strSalt);
        $data['sign'] = $sign;

        return $data;
    }
}
?>